package com.moonstar.controller;

import com.moonstar.config.SysConfig;
import com.moonstar.pojo.FileEntity;
import com.moonstar.pojo.Result;
import com.moonstar.service.FileService;
import com.moonstar.utils.FileType;
import com.moonstar.utils.FileUtil;
import com.moonstar.utils.PageUtils;
import com.moonstar.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传Controller
 *
 */
@Controller
@RequestMapping("/common/file")
public class FileController {

	@Autowired
	private FileService sysFileService;

	@Autowired
	private SysConfig sysConfig;

	@GetMapping()
	public String index() {
		return "file";
	}

	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<FileEntity> sysFileList = sysFileService.list(query);
		int total = sysFileService.count(query);
		PageUtils pageUtils = new PageUtils(sysFileList, total);
		return pageUtils;
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(Long id) {
		String fileName = sysConfig.getUploadPath() + sysFileService.get(id).getUrl().replace("/file/", "");
		if (sysFileService.remove(id) > 0) {
			boolean b = FileUtil.deleteFile(fileName);
			if (!b) {
				return Result.error("数据库记录删除成功，文件删除失败");
			}
			return Result.success();
		} else {
			return Result.error();
		}
	}



	@ResponseBody
	@PostMapping("/upload")
	public Result upload(@RequestParam("file") MultipartFile file) {
		String fileName = file.getOriginalFilename();
		fileName = FileUtil.renameToUUID(fileName);
		FileEntity sysFile = new FileEntity();
		sysFile.setType(FileType.fileType(fileName));
		sysFile.setUrl("/file/" + fileName);
		sysFile.setCreateDate(new Date());
		try {
			FileUtil.uploadFile(file.getBytes(), sysConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			return Result.error();
		}
		if (sysFileService.save(sysFile) > 0) {
			return Result.success().add("fileName", sysFile.getUrl());
		}
		return Result.error();
	}
}
